package com.jiezuo.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiezuo.auth.entity.Depart;
import com.jiezuo.auth.mapper.DepartMapper;
import com.jiezuo.auth.service.DepartService;
import com.jiezuo.common.exception.BusinessRuntimeException;
import com.jiezuo.common.util.PageUtil;
import com.jiezuo.common.util.StringUtil;
import com.jiezuo.common.util.VerifyUtil;
import com.jiezuo.common.vo.PageVo;
import org.flowable.common.engine.impl.util.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description 部门信息
 * @author 王帅
 * @date 2020/08/04 16:56
 * @version V1.0
 **/
@Service
public class DepartServiceImpl extends ServiceImpl<DepartMapper, Depart> implements DepartService {

    @Autowired
    DepartMapper departMapper;

    @Override
    public IPage<Depart> findPage(PageVo pageVo, Depart depart) {
        QueryWrapper<Depart> queryWrapper = new QueryWrapper<>();
        //查询条件,请根据需求，自行补充 TODO ...
        if (StringUtil.isNotEmpty(depart.getName())) {
            queryWrapper.like("name", depart.getName());
        }
        if (StringUtil.isNotEmpty(depart.getType())) {
            queryWrapper.eq("type", depart.getType());
        }
        if (StringUtil.isNotEmpty(depart.getStatus())) {
            queryWrapper.eq("status", depart.getStatus());
        }
        queryWrapper.ne("is_delete", "1");
        queryWrapper.orderByAsc("sort");
        IPage<Depart> page = this.page(PageUtil.initMpPage(pageVo), queryWrapper);
        // 只是为了，供前端使用  无意义
        for (Depart d : page.getRecords()) {
            d.setLabel(d.getName());
        }
        return page;
    }

    @Override
    public List<Depart> findList(Depart depart) {
        QueryWrapper<Depart> queryWrapper = new QueryWrapper<>();
        //查询条件,请根据需求，自行补充 TODO ...
        if (StringUtil.isNotEmpty(depart.getPid())) {
            queryWrapper.eq("pid", depart.getPid());
        }
        if (StringUtil.isNotEmpty(depart.getId())) {
            queryWrapper.eq("id", depart.getId());
        }
        if (StringUtil.isNotEmpty(depart.getType())) {
            queryWrapper.eq("type", depart.getType());
        }
        if (StringUtil.isNotEmpty(depart.getName())) {
            queryWrapper.like("name", depart.getName());
        }
        if (StringUtil.isNotEmpty(depart.getType())) {
            queryWrapper.eq("type", depart.getType());
        }
        if (StringUtil.isNotEmpty(depart.getIs_branch())) {
            queryWrapper.eq("is_branch", depart.getIs_branch());
        }
        if (StringUtil.isNotEmpty(depart.getIs_statistics())) {
            queryWrapper.eq("is_statistics", depart.getIs_statistics());
        }
        if (StringUtil.isNotEmpty(depart.getStatus())) {
            queryWrapper.eq("status", depart.getStatus());
        }
        if (StringUtil.isNotEmpty(depart.getIs_jiuzhou())) {
            queryWrapper.eq("is_jiuzhou", depart.getIs_jiuzhou());
        }
        if (StringUtil.isNotEmpty(depart.getIs_2025_version())) {
            queryWrapper.eq("is_2025_version", depart.getIs_2025_version());
        }
        queryWrapper.ne("is_delete", "1");
        queryWrapper.orderByAsc("sort");
        List<Depart> list = this.list(queryWrapper);
        // 只是为了，供前端使用  无意义
        for (Depart d : list) {
            d.setLabel(d.getName());
        }
        return list;
    }

    @Override
    public void saveDepart(Depart depart) {
        VerifyUtil.notEmpty("上级部门", depart.getPid());
        VerifyUtil.notEmpty("是否检测部门", depart.getIs_branch());
        VerifyUtil.notEmpty("所属企业", depart.getAffiliation_enterprise());
        VerifyUtil.notEmpty("部门编码", depart.getCode());
        //部门编码不能重复
        QueryWrapper<Depart> departQueryWrapper = new QueryWrapper<>();
        departQueryWrapper.eq("code", depart.getCode());
        departQueryWrapper.eq("is_delete", "0");
        List<Depart> departList = this.list(departQueryWrapper);
        if (!CollectionUtil.isEmpty(departList)) {
            throw new BusinessRuntimeException("该部门编码【" + depart.getCode() + "】已存在,请修改");
        }
        boolean bo = this.save(depart);
        if (!bo) {
            throw new BusinessRuntimeException("添加部门信息失败");
        }
        if ("0".equals(depart.getPid())) {
            depart.setAncestors(depart.getPid() + "," + depart.getId());
        } else {
            Depart d = this.getById(depart.getPid());
            depart.setAncestors(d.getAncestors() + "," + depart.getId());
        }
        boolean boo = this.updateById(depart);
        if (!boo) {
            throw new BusinessRuntimeException("修改部门信息失败");
        }
    }

    @Override
    public List<Map<String, String>> findUserDepart() {
        return departMapper.findUserDepart();
    }

    @Override
    public List<Depart> findDepartsByUserId(String user_id) {
        return departMapper.findDepartsByUserId(user_id);
    }

    @Override
    public List<Depart> getDepartTree(Depart depart) {
        String departName = depart.getName();
//        QueryWrapper<Depart> queryWrapper = new QueryWrapper<>();
//        if (StringUtil.isNotEmpty(depart.getAffiliation_enterprise())) {
//            queryWrapper.eq("affiliation_enterprise", depart.getAffiliation_enterprise());
//        }
//        queryWrapper.eq("is_delete", "0");
//        queryWrapper.orderByAsc("sort");
//        List<Depart> departList = this.list(queryWrapper);
        List<Depart> departList = departMapper.findAllList(depart);

        List<Depart> departs = iterateMenus(departList, "0", departName);
        return departs;
    }

    @Override
    public List<Depart> getDetectiveDepart() {
        QueryWrapper<Depart> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("is_delete", "1");
        queryWrapper.ne("is_branch", "0");
        queryWrapper.eq("status", "1");
        queryWrapper.orderByAsc("sort");
        List<Depart> departList = this.list(queryWrapper);
        return departList;
    }

    @Override
    public List<Depart> findGather() {
        return departMapper.findGather();
    }

    @Override
    public int updateDepart(Depart depart) {
        return departMapper.updateDepart(depart);
    }

    /**
     *多级部门查询方法
     * @param pid 父类id
     * @return
     */
    public List<Depart> iterateMenus(List<Depart> departList, String pid, String departName) {
        List<Depart> parents = departList.stream().filter(it -> pid.equals(it.getPid())).collect(Collectors.toList());
        Iterator<Depart> iterator = parents.iterator();
        while (iterator.hasNext()) {
            Depart depart = iterator.next();
            if (StringUtil.isNotEmpty(departName) && !isSelfAndChildrenByName(departList, depart, departName)) {
                iterator.remove();//移除
            }
            //获取部门的id
            String departId = depart.getId();
            if (isHasChildren(departList, departId)) {
                List<Depart> childrens = iterateMenus(departList, departId, departName);
                depart.setChildren(childrens);
            }
        }
        return parents;
    }

    // 判断是否还有子级
    public boolean isHasChildren(List<Depart> departList, String id) {
        return departList.stream().filter(it -> id.equals(it.getPid())).findFirst().isPresent();
    }

    // 判断自己和子级中是否包含这个部门名称（模糊查询）
    public boolean isSelfAndChildrenByName(List<Depart> departList, Depart parent, String departName) {
        boolean isContain = parent.getName().contains(departName);
        isContain = isChildrenContain(departList, parent.getId(), departName, isContain);
        return isContain;
    }

    public boolean isChildrenContain(List<Depart> departList, String pId, String departName, boolean isContain) {
        if (!isContain) {//自己不包含，继续查
            List<Depart> childrens = departList.stream().filter(it -> it.getPid().equals(pId)).collect(Collectors.toList());//子级
            for (Depart children : childrens) {
                isContain = children.getName().contains(departName);
                if (isContain) {
                    break;
                }
            }
            if (!isContain) {//子级均不包含,继续
                for (Depart children : childrens) {
                    isContain = isChildrenContain(departList, children.getId(), departName, isContain);
                    if (isContain) {
                        break;
                    }
                }
            }
        }
        return isContain;
    }

}
